<template>
  <a-modal
    :visible="visible"
    @ok="handleSubmit"
    @cancel="closeModal"
    :maskClosable="false"
    :keyboard="false"
    :confirmLoading="loading"
    :width="480"
    title="修改密码"
  >
    <a-form :form="form">
      <a-form-item v-bind="formItemLayout" label="旧密码">
        <a-input
          type="password"
          v-decorator="[
            'password',
            { rules: [{ required: true, message: '请输入旧密码!' }] },
          ]"
        />
      </a-form-item>
      <a-form-item v-bind="formItemLayout" label="新密码">
        <a-input
          type="password"
          v-decorator="[
            'newPassword',
            {
              rules: [
                { required: true, message: '请输入新密码!' },
                {
                  pattern: /^[a-zA-Z0-9]{4,16}$/g,
                  message: '密码必须为4-16位的字母数字组合',
                },
                { validator: validateToNextPassword },
              ],
            },
          ]"
        />
      </a-form-item>
      <a-form-item v-bind="formItemLayout" label="确认密码">
        <a-input
          type="password"
          v-decorator="[
            'confirm',
            {
              rules: [
                { required: true, message: '请在此输入密码!' },
                {
                  pattern: /^[a-zA-Z0-9]{4,16}$/g,
                  message: '密码必须为4-16位的字母数字组合',
                },
                { validator: compareToFirstPassword },
              ],
            },
          ]"
          @blur="handleConfirmBlur"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script>
import { updateUserInfo, logout } from '@/services/user';
import { mapGetters } from 'vuex';
export default {
  props: {
    visible: {
      type: Boolean,
      required: true,
    },
  },
  data() {
    return {
      form: this.$form.createForm(this),
      loading: false,
      confirmDirty: false,
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 18 },
      },
    };
  },
  methods: {
    handleSubmit() {
      const { getFieldValue } = this.form;
      this.form.validateFields(async (err) => {
        if (err) return;

        this.loading = true;
        let params = {};
        if (this.user.password != getFieldValue('password')) {
          this.$message.error('旧密码输入错误');
          this.loading = false;
          return;
        }
        params = this.user;
        params.password = getFieldValue('newPassword').toString();
        updateUserInfo(params)
          .then((res) => {
            this.closeModal();
            this.loading = false;
            this.$message.success({
              title: res.msg,
              content: '恭喜你，密码修改成功，请重新登录',
              onClose: () => {
                logout();
                this.$router.replace('/login');
              },
            });
          })
          .catch((err) => {
            this.$message.error(err);
          });
      });
    },
    closeModal() {
      this.form.resetFields();
      this.$emit('close');
    },
    handleConfirmBlur(e) {
      const value = e.target.value;
      this.confirmDirty = this.confirmDirty || !!value;
    },
    compareToFirstPassword(rule, value, callback) {
      rule;
      const form = this.form;
      if (value && value !== form.getFieldValue('newPassword')) {
        callback(new Error('两次输入的密码不一致!'));
      } else {
        callback();
      }
    },
    validateToNextPassword(rule, value, callback) {
      rule;
      const form = this.form;
      if (value && this.confirmDirty) {
        form.validateFields(['confirm'], { force: true });
      }
      callback();
    },
  },
  computed: {
    ...mapGetters('account', ['user']),
  },
};
</script>
